#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''

import urllib.parse,json
from com.zxy.common import Com_Para
from com.zxy.common.Com_Fun import Com_Fun
from com.zxy.model.Return_Value import Return_Value
from com.zxy.adminlog.UsAdmin_Log import UsAdmin_Log
from _operator import length_hint
import sys,csv,re,xlrd
import collections as col
from openpyxl import load_workbook                        
from com.zxy.z_debug import z_debug
class Request_back(z_debug):
    attStrIP = ""
    attServSocket = None
    attUri = ""
    attPost_str = []
    attRv = Return_Value()
    attUploadFile = ""
    attConnection = ""
    def __init__(self):
        pass
    def parseUri(self,inputValue):
        temStrResult = ""
        if inputValue.find("/favicon.ico") != -1:
            temStrResult += "favicon.ico"
            return temStrResult
        elif inputValue.find(Com_Para.Inf_Name) != -1:
            for temStrITem in inputValue.split("\r\n"):
                if temStrITem.find(Com_Para.Inf_Name) != -1:
                    if (temStrITem.split(" ")[1]).find("?") != -1:
                        temStrResult += urllib.parse.unquote(temStrITem.split(" ")[1].split("?")[1])
                    else:
                        temStrResult += urllib.parse.unquote(temStrITem.split(" ")[1])
                    break
        elif self.FindWebName(inputValue):
            for temStrITem in inputValue.split("\r\n"):
                if self.FindWebName(temStrITem):
                    temStrT = temStrITem.split(" ")[1]
                    if temStrT.find("?") == -1:
                        temStrResult = urllib.parse.unquote(temStrITem.split(" ")[1],Com_Para.U_CODE)
                    else:
                        temStrResult = urllib.parse.unquote(temStrT[0:temStrT.find("?")],Com_Para.U_CODE)
                    break
        elif len(inputValue) > 10:
            temStrResult = inputValue
        return temStrResult
    def FindWebName(self,inputValue):
        for temAttF in Com_Para.web_Name:
            if inputValue.find(temAttF) != -1:
                return True
        return False
    def PostData(self,inputValue):
        temStrResult = ["",""]
        if self.FindWebName(inputValue):
            temStrTem = inputValue.split("\r\n")
            if len(temStrTem[0].split(" ")) > 1 and (temStrTem[0].split(" ")[0] == "POST" or temStrTem[0].split(" ")[0] == "OPTIONS") :
                temContent_Length = -1
                temStrEnd = inputValue[len(inputValue) - 4:len(inputValue)]
                if temStrEnd != "\r\n\r\n":
                    temStrResult[1] = temStrTem[len(temStrTem) - 1]
                for temStrItem in temStrTem:
                    temStrItem = urllib.parse.unquote(temStrItem,Com_Para.U_CODE)
                    if temStrItem.find("post_param: ") == 0:
                        temStrResult[1] = temStrItem[temStrItem.find("post_param: ") + 12:len(temStrItem)]
                        temStrResult[0] = "Content-Length:"
                        temStrResult[0] += str(len(temStrResult[1]))
                        break
                    if temStrItem.find("Content-Length:") == 0:
                        temContent_Length = int(temStrItem.split(":")[1].strip())
                        temStrResult[0] = "Content-Length:"
                        temStrResult[0] += str(temContent_Length)
                    if temContent_Length > 0 and temContent_Length == len(temStrResult[1].encode(Com_Para.U_CODE)):
                        break
        return temStrResult
    def GetHttpHead(self,inputValue):
        temResult = {}
        for temStrITem in inputValue.split("\r\n"):
            if temStrITem.find("POST") == 0 or temStrITem.find("GET") == 0:                
                strKey = temStrITem.split(" ")[0]          
                strValue = temStrITem.split(" ")[1]
            else:
                strKey = temStrITem[0:temStrITem.find(":")]            
                strValue = temStrITem[len(strKey)+1:len(temStrITem)]
            if Com_Fun.GetHashTableNone(temResult, strKey) == None:
                Com_Fun.SetHashTable(temResult, strKey, strValue)
        return temResult
    def GetHttpHeadArray(self,inputValue,boundary):
        temResult = []
        bFlag = False
        for temStrITem in inputValue.split("\r\n"):
            if temStrITem == "--"+boundary:   
                bFlag = True                
            if bFlag == True:
                temResult.append(temStrITem)
        return temResult
    def parse(self):        
        temInit_msg = b'' # 初始化流
        temFile = None
        temValue = ""
        try:        
            temInit_msg = self.attServSocket.recv(20480) #接受数据  20480
            temStrCheck = []
            try:
                temValue = temInit_msg.decode(Com_Para.U_CODE)
            except Exception as et:
                if temInit_msg.find(b"\r\n\r\n") == -1:
                    return
                else:
                    temValue = temInit_msg[0:temInit_msg.find(b"\r\n\r\n")].decode(Com_Para.U_CODE)
            inputHtHead = self.GetHttpHead(temValue)
            self.attConnection = Com_Fun.GetHashTable(inputHtHead,"Connection")
            self.attUri = self.parseUri(temValue)
            temStrCheck = self.PostData(temValue)
            if temStrCheck[0] != "" and int(temStrCheck[0].split(":")[1].strip()) == len(temStrCheck[1].encode(Com_Para.U_CODE)):
                self.attPost_str = urllib.parse.unquote(temStrCheck[1].replace("+","%20"),Com_Para.U_CODE).split("&")
                if temStrCheck[1] != "":
                    self.attUri += "&" + urllib.parse.unquote(temStrCheck[1].replace("+","%20"),Com_Para.U_CODE)                
            elif temStrCheck[0] != "" and int(temStrCheck[0].split(":")[1].strip()) > 0:
                if self.attUri.find("param_name=upLoadFile") != -1:
                    bSaveFile = False
                    iAllLength = int(temStrCheck[0].split(":")[1].strip())
                    if Com_Fun.GetHashTable(inputHtHead,"Content-Type").find("boundary=") == -1:
                        boundary = Com_Fun.Get_New_GUID()
                    else:
                        boundary = Com_Fun.GetHashTable(inputHtHead,"Content-Type").split(";")[1].split("=")[1]
                    oldFileName = []
                    newFileName = []
                    temFile_dataAry = []
                    bFlagF = -1
                    while iAllLength > 0:
                        temFile_data = b''
                        if Com_Fun.GetHashTableNone(inputHtHead, "Content-Disposition") != None and len(temFile_dataAry) == 0:
                            inputAryHead = self.GetHttpHeadArray(temValue,boundary)
                            bBegin = 0
                            temFile_data =  ("--"+boundary+"\r\n").encode(Com_Para.U_CODE)            
                            for strlin in inputAryHead:
                                if strlin.find("Content-Disposition: form-data") == 0:
                                    cdAry = strlin.split(";")
                                    if len(cdAry) == 3 and cdAry[2].find("filename=") == 1 and bBegin == 0:
                                        bBegin = 1
                                elif strlin.find("Content-Type:") == 0 and bBegin == 1:
                                    bBegin = 2
                                elif strlin == "" and bBegin == 2:
                                    bBegin = 3
                                if bBegin > 0:
                                    temFile_data = temFile_data+(strlin+"\r\n").encode(Com_Para.U_CODE)
                        else:
                            temFile_data = self.attServSocket.recv(iAllLength)
                        temFile_dataAry = temFile_data.split(b'\n')
                        iC = 0
                        for RC in temFile_dataAry:
                            try:
                                temStrV = RC.decode(Com_Para.U_CODE)
                            except Exception as es:
                                temStrV = ""
                            if temStrV.find("--"+boundary) == 0:
                                if temFile is not None:
                                    bSaveFile = True
                                    temFile.close()
                                    temFile = None
                            if temStrV.find("Content-Disposition: form-data") == 0:
                                cdAry = temStrV.split(";")
                                if len(cdAry) == 3 and cdAry[2].find("filename=") == 1:
                                    bFlagF = 0                     
                                else:
                                    bFlagF = -1
                            if bFlagF == 0 and temStrV.find("Content-Disposition:") == 0:
                                oldN = temStrV.split(":")[1].split(";")[2].split("=")[1].replace("\r","").replace("\n","").replace("\"","")
                                if oldN != "" and oldN.find(".") != -1:
                                    if Com_Para.attUpFile.find(oldN.split(".")[1].lower()+"|") == -1:
                                        oldFileName.append("不符合上传文件格式，上传失败:"+oldN)
                                        newFileName.append("不符合上传文件格式，上传失败:"+oldN)
                                    else:
                                        oldFileName.append(oldN)                                
                                        if oldN.find(".") == -1:
                                            newFileName.append(Com_Fun.Get_New_GUID().replace("-", "")+".no")                                
                                        else:
                                            newFileName.append(Com_Fun.Get_New_GUID().replace("-", "")+"."+oldN.split(".")[1])
                                        strF = Com_Para.ApplicationPath+Com_Para.zxyPath+"web"+Com_Para.zxyPath+"file"+Com_Para.zxyPath+newFileName[len(newFileName) - 1]
                                        temFile = open(strF, "wb")
                                        bFlagF = 1
                            elif bFlagF == 1 and temStrV == "\r":
                                bFlagF = 2
                            elif bFlagF == 2 and temFile is not None:
                                temFile.write(RC)
                                if iC != len(temFile_dataAry) - 1:              
                                    temFile.write(b'\n')
                            iC = iC + 1
                        iAllLength = iAllLength - len(temFile_data)   
                    if temFile is not None:
                        bSaveFile = True
                        temFile.close()
                        temFile = None
                    if bSaveFile == False:                        
                        self.attRv.s_result = 0
                        self.attRv.err_desc = "文件上传失败,请刷新网络或重新上传"
                        self.attUploadFile = "{\"A01_UpLoadFile\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"0\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"上传失败,请刷新网络或重新上传\"}]}"
                        return
                    jso = {}
                    jsary = []
                    iIndex = 0
                    for temItem in oldFileName:
                        temjso = {}
                        temjso[Com_Fun.GetLowUpp("oldFileName")] = temItem
                        temjso[Com_Fun.GetLowUpp("newFileName")] = newFileName[iIndex]
                        jsary.append(temjso) 
                        iIndex = iIndex + 1    
                    jso["A01_UpLoadFile"] = jsary                        
                    self.attUploadFile = json.dumps(jso,ensure_ascii=False)       
                else:                
                    temStrCheck[1] = ""                
                    temInit_msg = b''
                    temInit_msg = self.attServSocket.recv(20480)
                    temStrCheck[1] = urllib.parse.unquote(temInit_msg.decode(Com_Para.U_CODE),Com_Para.U_CODE)   
                    self.attPost_str = temStrCheck[1].split("&")
                    if temStrCheck[1] != "":
                        self.attUri += "&" + temStrCheck[1]
        except Exception as e:
            self.attRv.s_result = 0
            self.attRv.err_desc = repr(e)
            self.attUploadFile = "{\"A01_UpLoadFile\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"0\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"上传失败,请刷新网络或重新上传\""+ repr(e)+"}]}"
        finally:
            if temFile is not None:
                temFile.close()
                temFile = None
            pass